﻿using System;
using System.Web;

namespace ImageGallery.DAL
{
    public class EntitiesModelManager
    {
        private const string EntitiesModel = "EntitiesModel";
        /// <summary></summary>
        /// Creates new EntitiesModel and stores it in the current thread's model.
        /// If EntitiesModel already exists, do nothing.
        ///
        public static void CreateIGEntitiesModel()
        {
            EntitiesModel igEntitiesModel = (EntitiesModel)HttpContext.Current.Items[EntitiesModel]; //Thread.GetData(EntitiesModelSlot);
            if (igEntitiesModel == null)
            {
                igEntitiesModel = new EntitiesModel();
                HttpContext.Current.Items.Add("EntitiesModel", igEntitiesModel);
            }
        }

        /// <summary></summary>
        /// Return the EntitiesModel associated with the current thread.
        /// Throws and InvalidOperationException if no data model is associated with the current thread.
        ///
        public static EntitiesModel IGEntitiesModel
        {
            get
            {
                EntitiesModel igEntitiesModel = HttpContext.Current.Items[EntitiesModel] as EntitiesModel;
                if (igEntitiesModel != null)
                {
                    return igEntitiesModel;
                }
                else
                {
                    throw new InvalidOperationException(
                    "The Entity Diagrams is not found in the current thread's context.");
                }
            }
        }

        /// <summary></summary>
        /// Disposes the EntitiesModel currently associated with the current thread
        /// and removes it from the thread context. If no data context is asssociated
        /// with the current thread, does nothing.
        ///
        public static void DisposeIGEntitiesModel()
        {
            EntitiesModel igEntitiesModel = HttpContext.Current.Items[EntitiesModel] as EntitiesModel;
            if (igEntitiesModel != null)
            {
                igEntitiesModel.Dispose();
            }
        }
    }
}
